<template>
  <el-drawer v-model="formCtrl.isDrawerOpen" class="farm2-data-form" :append-to-body="true" :with-header="false"
    size="500px">
    <div class="title">{{ currentFormType.type.title }}数据</div>
    <el-form :show-message="formCtrl.isShowValidMsg" v-loading="isLoading" :model="form" label-width="auto"
      ref="ruleFormRef" :disabled="!formCtrl.isAbledForm">
      <el-form-item label="主鍵:" prop="id" v-if="isShowform.id" :rules="v.getRules(true, 0, 16)">
        <el-input v-model="form.id" />
      </el-form-item>
      <el-form-item label="修改时间:" prop="etime" v-if="isShowform.etime" :rules="v.getRules(true, 0, 7)">
        <el-input v-model="form.etime" />
      </el-form-item>
      <el-form-item label="名称：" prop="name" v-if="isShowform.name" :rules="v.getRules(true, 0, 128)">
        <el-input v-model="form.name" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="模型类型：" prop="funckey" v-if="isShowform.funckey" :rules="v.getRules(true)">
        <el-select v-model="form.funckey" placeholder="请选择">
          <el-option label="对话模型" value="TALK" />
          <el-option label="向量模型" value="EMB" />
        </el-select>
      </el-form-item>
      <el-form-item label="实现类CLASS：" prop="implclass" v-if="isShowform.implclass" :rules="v.getRules(true, 0, 256)">
        <el-select v-model="form.implclass" placeholder="请选择">
          <el-option label="com.farm2.llm.client.impl.Farm2LlmPlexPtClientImpl"
            value="com.farm2.llm.client.impl.Farm2LlmPlexPtClientImpl" />
            <el-option label="com.farm2.llm.client.impl.Farm2EmbedAliyunClientImpl"
            value="com.farm2.llm.client.impl.Farm2EmbedAliyunClientImpl" />
            <el-option label="com.farm2.llm.client.impl.Farm2EmbedOllamaClientImpl"
            value="com.farm2.llm.client.impl.Farm2EmbedOllamaClientImpl" />
        </el-select>
      </el-form-item>
      <el-form-item label="baseUrl：" prop="baseurl" v-if="isShowform.baseurl" :rules="v.getRules(true, 0, 256)">
        <el-input v-model="form.baseurl" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="apiKey：" prop="apikey" v-if="isShowform.apikey" :rules="v.getRules(false, 0, 256)">
        <el-input v-model="form.apikey" type="password" show-password autosize />
      </el-form-item>
      <el-form-item label="modelKey：" prop="modelkey" v-if="isShowform.modelkey" :rules="v.getRules(true, 0, 256)">
        <el-input v-model="form.modelkey" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="tokenSize:" prop="tokensize" v-if="isShowform.tokensize" :rules="v.getRules(true)">
        <el-input-number v-model="form.tokensize" />
      </el-form-item>
      <el-form-item label="向量尺寸:" prop="dimensions" v-if="isShowform.dimensions" :rules="v.getRules(false)">
        <el-input-number v-model="form.dimensions" />
      </el-form-item>
      <el-form-item label="向量格式:" prop="enformat" v-if="isShowform.enformat" :rules="v.getRules(false)">
        <el-input v-model="form.enformat" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="代理IP:" prop="proxyip" v-if="isShowform.proxyip" :rules="v.getRules(false, 0, 32)">
        <el-input v-model="form.proxyip" />
      </el-form-item>
      <el-form-item label="代理端口:" prop="proxyport" v-if="isShowform.proxyport" :rules="v.getRules(false)">
        <el-input-number v-model="form.proxyport" />
      </el-form-item>
      <el-form-item label="状态：" prop="state" v-if="isShowform.state" :rules="v.getRules(true)">
        <el-select v-model="form.state" placeholder="请选择">
          <el-option label="可用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注：" prop="note" v-if="isShowform.note" :rules="v.getRules(false, 0, 256)">
        <el-input v-model="form.note" autosize type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-row class="farm2-form-button">
          <el-col :span="14">
            <el-button v-if="formCtrl.isShowSubmit" type="primary" @click="onSubmitForm(addData)">提交{{
              currentFormType.type.title }}</el-button>
            <el-switch v-if="formCtrl.isShowRetain" v-model="isRetainForm" size="small" inactive-text="提交后保留表单" />
          </el-col>
          <el-col :span="10" class="farm2-right">
            <el-button v-if="formCtrl.isShowReset" type="warning" @click="onResetForm">清空</el-button>
            <el-button v-if="formCtrl.isShowSubmit" type="info" plain @click="drawerWinOpen(false)">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script lang="ts" setup>

import { inject, onMounted, reactive, ref } from 'vue';
import v from '@/hook/farmFormValids';
import farm2Request from '@/service/remoteRequests/Farm2Request';
import { RequestTypeEnum } from '@/types/commons/RequestTypeEnum';
import notice from '@/components/msg/FarmNotice';
import { getCreatType, getUpdateType, getViewType, type FormParam } from '@/types/commons/FormType';
import type { DataResponse } from '@/types/commons/DataResponse';
import type { Emitter, EventType } from 'mitt';
import { PageEvent } from '@/types/commons/PageEvent';
import farmFormUtils from '@/hook/farmFormUtils';
const eventBus = inject('eventBus') as Emitter<Record<EventType, unknown>>;
const ruleFormRef = ref()
const isLoading = ref(false);
const isRetainForm = ref(false);
const currentFormType = reactive<FormParam>({ type: getViewType(), id: '', data: {} });


const formCtrl = reactive({
  isShowRetain: true,
  isShowSubmit: true,
  isDrawerOpen: false,
  isAbledForm: false,
  isShowReset: true,
  isShowValidMsg: true,
});


const isShowform = reactive({
  id: true,
  state: false,
  note: true,
  etime: true,
  name: true,
  implclass: true,
  apikey: true,
  baseurl: true,
  modelkey: true,
  tokensize: true,
  proxyip: true,
  proxyport: true,
  funckey: false,
  modellevel: false,
  dimensions: false,
  enformat: false,
});


const form = reactive({
  id: '',
  state: '0',
  note: '',
  etime: '',
  name: '',
  implclass: '',
  apikey: '',
  baseurl: '',
  modelkey: '',
  tokensize: 1,
  proxyip: '',
  proxyport: 1,
  funckey: '',
  modellevel: '',
  dimensions: '',
  enformat: ''
})


/**
 * 打开或关闭表单窗口
 * @param isOpen
 * @param formType
 */
const drawerWinOpen = (isOpen: boolean, formParam?: FormParam) => {
  if (!isOpen) {
    formCtrl.isDrawerOpen = isOpen;
  } else {
    if (formParam?.type.key !== currentFormType?.type.key) {
      ruleFormRef.value?.resetFields();
    }
    Object.assign(currentFormType, formParam);
    if (formParam?.type.key == getCreatType().key) {
      initCreatForm(formParam);
    }
    if (formParam?.type.key == getUpdateType().key) {
      initUpdateForm(formParam.id);
    }
    if (formParam?.type.key == getViewType().key) {
      initViewForm(formParam.id);
    }
  }
};

/**
 * 初始化创建窗口
 */
const initCreatForm = (formParam: FormParam) => {
  farmFormUtils.initFormCtrl(getCreatType(), formCtrl);
  formCtrl.isShowValidMsg = true;
  Object.assign(isShowform, {
    id: false,
    state: false,
    note: true,
    etime: false,
    name: false,
    implclass: true,
    apikey: false,
    baseurl: false,
    modelkey: false,
    tokensize: false,
    proxyip: false,
    proxyport: false,
    funckey: true,
    dimensions: false,
    enformat: false,
  });
  if (formParam) {

  }
}

/**
 * 初始化更新窗口
 * @param id
 */
const initUpdateForm = (id: string | undefined) => {
  farmFormUtils.initFormCtrl(getUpdateType(), formCtrl);
  if (!id) {
    notice.byError("id不能为空");
  } else {
    formCtrl.isShowValidMsg = true;
    viewData(id, () => {
      if (form.funckey == 'TALK') {
        Object.assign(isShowform, {
          id: false,
          state: true,
          note: true,
          etime: false,
          name: false,
          implclass: false,
          apikey: true,
          baseurl: true,
          modelkey: true,
          tokensize: true,
          proxyip: true,
          proxyport: true,
          funckey: false,
          dimensions: false,
          enformat: false,
        });
      }
      if (form.funckey == 'EMB') {
        Object.assign(isShowform, {
          id: false,
          state: true,
          note: true,
          etime: false,
          name: false,
          implclass: false,
          apikey: true,
          baseurl: true,
          modelkey: true,
          tokensize: false,
          proxyip: true,
          proxyport: true,
          funckey: false,
          dimensions: true,
          enformat: true,
        });
      }
    });
  }
}

/**
 * 初始化浏览窗口
 * @param id
 */
const initViewForm = (id: string | undefined) => {
  farmFormUtils.initFormCtrl(getViewType(), formCtrl);
  if (!id) {
    notice.byError("id不能为空");
  } else {
    formCtrl.isShowValidMsg = false;
    viewData(id);
    Object.assign(isShowform, {
      id: true,
      state: true,
      note: false,
      etime: true,
      name: true,
      implclass: true,
      apikey: true,
      baseurl: true,
      modelkey: true,
      tokensize: true,
      proxyip: true,
      proxyport: true,
      funckey: true,
    });
  }
}

/**
 * 展示信息（加载用户信息）
 */
const viewData = async (id: string, func?: () => void) => {
  farm2Request.submit('api/llmclient/' + id, RequestTypeEnum.get, isLoading).then((response: DataResponse) => {
    Object.assign(form, response.data)
    if (func) {
      func();
    }
  }).catch((msg: string) => {
    notice.byError(msg);
  });
}

/**
 * 执行提交按钮（创建/更新）
 */
const addData = async () => {

  if (currentFormType.type.key == getCreatType().key) {
    farm2Request.submit('api/llmclient', RequestTypeEnum.post, isLoading, form).then(() => {
      notice.bySuccess("创建成功!");
      eventBus.emit(PageEvent.data_do_query);
      if (!isRetainForm.value) {
        onResetForm();
        drawerWinOpen(false);
      }
    }).catch((msg: string) => {
      notice.byError(msg);
    });
  }

  if (currentFormType.type.key == getUpdateType().key) {
    farm2Request.submit('api/llmclient/' + form.id, RequestTypeEnum.put, isLoading, form).then(() => {
      notice.bySuccess("更新成功!");
      eventBus.emit(PageEvent.data_do_query);
      onResetForm();
      drawerWinOpen(false);
    }).catch((msg: string) => {
      notice.byError(msg);
    });
  }
}


/**清空表单 */
const onResetForm = () => {
  ruleFormRef.value.resetFields();
}

/**
 * 校验表单，准备提交
 * @param func
 */
const onSubmitForm = async (func: () => void) => {
  await ruleFormRef.value.validate((valid: boolean) => { if (valid) { func() } });
}

onMounted(() => {
  eventBus.on(PageEvent.data_form_open, (paras) => {
    drawerWinOpen((paras as { isOpen: boolean }).isOpen, (paras as { type: FormParam }).type);
  })
});
</script>
